# -*- coding:utf-8 -*-
import joblib
import os
import time

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier

from preprocess_data import get_data

class PCAKNN(object):
    """docstring for PCAKNN"""
    def __init__(self,n_components = 30,n_neighbors = 5):
        super(PCAKNN, self).__init__()
        self.save_dir = 'saved_models'
        self.n_components = n_components
        self.n_neighbors = n_neighbors

    def train(self,save_model = True,model_path = None):
        train_features,train_labels = get_data('训练集')
        pipe_lr = Pipeline([('sc', StandardScaler()),
                            ('pca', PCA(n_components=self.n_components)),
                            ('clf', KNeighborsClassifier(n_neighbors=self.n_neighbors))
                            ])
        print('n_components=%d, n_neighbors=%d'%(self.n_components,self.n_neighbors))
        print('training...')
        t = time.time()
        pipe_lr.fit(train_features, train_labels)
        print('train time:%.2fs'%(time.time()-t)) 
        if save_model:
            if model_path == None:
                model_path = self.save_dir + '/PACKNN.m'
            joblib.dump(pipe_lr,model_path)
        print('save model to %s\ndone.'%model_path)

    def test(self,model_path=None):
        if model_path == None:
            model_path = self.save_dir + '/PACKNN.m'
        assert os.path.exists(model_path),'no find model_path:%s'%(model_path)
        print('testing...\nload model from %s[train]'%model_path)
        test_features,test_labels = get_data('训练集')
        test_features,test_labels = test_features[:1000],test_labels[:1000] 
        pipe_lr = joblib.load(model_path)
        t = time.time()
        score = pipe_lr.score(test_features,test_labels)
        print('acc = %2.2f%%; \ndone. '%(score*100))
        print('test time[train]:%.2fs'%((time.time()-t)*28.8))

        print('testing...\nload model from %s[test]'%model_path)
        test_features,test_labels = get_data('测试集')
        pipe_lr = joblib.load(model_path)
        t = time.time()
        score = pipe_lr.score(test_features,test_labels)
        print('acc = %2.2f%%; \ndone. '%(score*100))
        print('test time[test]:%.2fs'%(time.time()-t))

